import { setToken, getToken } from '@/utils/auth.js'
import { login, getProfile } from '@/api/user'
import { resetRouter } from '@/router/index.js'

const state = {
  // 登录-初始化token
  token: getToken() || null,
  // 用户个人信息
  userInfo: {}
}

const mutations = {
  // 登录-操作token
  setToken(state, newToken) {
    state.token = newToken
    setToken(newToken)
  },
  // 用户个人信息
  setuserInfo(state, newuserInfo) {
    state.userInfo = newuserInfo
  }
}

const actions = {
  // 登录-发请求
  async login(context, n) {
    // console.log(context, n)
    const res = await login(n)
    // console.log('actions login', res)
    const token = res.data
    context.commit('setToken', token)
  },
  // 获取用户基本信息-发请求
  async getProfile(context) {
    const res = await getProfile()
    // console.log(res.data)
    context.commit('setuserInfo', res.data)
    return res.data
  },
  // 退出
  logout(context) {
    context.commit('setToken', '')
    context.commit('setuserInfo', {})
    resetRouter()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
